from flask import Blueprint, request, jsonify
from werkzeug.exceptions import BadRequest
from app import db
from app.tags.models import Tag
from app.tags.schemas import tag_schema, tags_schema

# 创建标签模块的蓝图
tags_bp = Blueprint('tags', __name__)

@tags_bp.route('', methods=['GET'])
def get_tags():
    """
    获取所有标签列表
    ---
    响应：标签列表
    """
    tags = Tag.query.all()
    return jsonify(tags_schema.dump(tags))
    # return jsonify({'message': '返回一手标签列表'}), 200

@tags_bp.route('/<int:tag_id>', methods=['GET'])
def get_tag(tag_id):
    """
    获取单个标签的详细信息
    ---
    参数：tag_id - 标签ID
    响应：标签详细信息
    """
    tag = Tag.query.get_or_404(tag_id)
    return jsonify(tag_schema.dump(tag))

@tags_bp.route('', methods=['POST'])
def create_tag():
    """
    创建新标签
    ---
    请求体：标签信息
    响应：创建成功的标签信息
    """
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 验证必填字段
    if 'name' not in data:
        raise BadRequest('Missing required field: name')
    
    # 检查标签名称是否已存在
    if Tag.query.filter_by(name=data['name']).first():
        raise BadRequest('Tag name already exists')
    
    # 创建标签对象
    tag = Tag(
        name=data['name']
    )
    
    db.session.add(tag)
    db.session.commit()
    
    return jsonify(tag_schema.dump(tag)), 201

@tags_bp.route('/<int:tag_id>', methods=['PUT'])
def update_tag(tag_id):
    """
    更新标签信息
    ---
    参数：tag_id - 标签ID
    请求体：更新的标签信息
    响应：更新后的标签信息
    """
    tag = Tag.query.get_or_404(tag_id)
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 检查是否更新了名称，如果更新了则检查唯一性
    if 'name' in data and data['name'] != tag.name:
        if Tag.query.filter_by(name=data['name']).first():
            raise BadRequest('Tag name already exists')
        tag.name = data['name']
    
    db.session.commit()
    
    return jsonify(tag_schema.dump(tag))

@tags_bp.route('/<int:tag_id>', methods=['DELETE'])
def delete_tag(tag_id):
    """
    删除标签
    ---
    参数：tag_id - 标签ID
    响应：成功删除的消息
    """
    tag = Tag.query.get_or_404(tag_id)
    
    db.session.delete(tag)
    db.session.commit()
    
    return jsonify({'message': 'Tag deleted successfully'})

@tags_bp.route('/search', methods=['GET'])
def search_tags():
    """
    搜索标签
    ---
    参数：q - 搜索关键词
    响应：匹配的标签列表
    """
    keyword = request.args.get('q', '')
    if not keyword:
        return jsonify(tags_schema.dump([]))
    
    tags = Tag.query.filter(
        Tag.name.contains(keyword)
    ).all()
    
    return jsonify(tags_schema.dump(tags))

@tags_bp.route('/<int:tag_id>/recipes', methods=['GET'])
def get_recipes_by_tag(tag_id):
    """
    获取指定标签的所有食谱
    ---
    参数：tag_id - 标签ID
    响应：食谱列表
    """
    tag = Tag.query.get_or_404(tag_id)
    from app.recipes.schemas import recipes_simple_schema
    return jsonify(recipes_simple_schema.dump(tag.recipes))